<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"anynone.gitee.io","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.7.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>
<meta property="og:type" content="website">
<meta property="og:title" content="anynone">
<meta property="og:url" content="https://anynone.gitee.io/page/16/index.html">
<meta property="og:site_name" content="anynone">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="山丘之王">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://anynone.gitee.io/page/16/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":true,"isPost":false,"lang":"zh-CN","comments":"","permalink":"","path":"page/16/index.html","title":""}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>anynone</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">anynone</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <img src="/images/head.jpg">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">山丘之王</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">22</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/anynone" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;anynone" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner index posts-expand">

    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://anynone.gitee.io/2021/09/27/phalcon-session-md/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="山丘之王">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="anynone">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2021/09/27/phalcon-session-md/" class="post-title-link" itemprop="url">phalcon自定义session_id</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-09-27 23:27:42" itemprop="dateCreated datePublished" datetime="2021-09-27T23:27:42+08:00">2021-09-27</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-09-09 08:09:56" itemprop="dateModified" datetime="2022-09-09T08:09:56+08:00">2022-09-09</time>
      </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <p>phalcon基于di容器管理所有服务，session也做为服务被引入。正常情况下要实现自定义session_id只要在session_start前使用session_id函数设置即可。但是，一般逻辑是先检查session是否存在用户信息，如果存在表示登陆，不存在表示游客。要获取session信息必须先session_start，因此想要真正自定义session_id，要在返回cookie头前对session_id进行修改。
php提供了一个函数session_regenerate_id（），允许使用新生成的会话 ID 更新现有会话 ID，并且不会修改用户信息。基于这个思路，注入di容器的session服务如下</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">$di</span>-&gt;setShared(<span class="string">&#x27;session&#x27;</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="variable">$session</span> = <span class="keyword">new</span> <span class="class"><span class="keyword">class</span>() <span class="keyword">extends</span> <span class="title">SessionManager</span></span>&#123;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="variable">$factory</span> = <span class="keyword">new</span> SerializerFactory();</span><br><span class="line">    <span class="variable">$adapterFactory</span> = <span class="keyword">new</span> AdapterFactory(<span class="variable">$factory</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="variable">$redis</span> = <span class="keyword">new</span> <span class="class"><span class="keyword">class</span>($<span class="title">adapterFactory</span>, <span class="title">array_merge</span>([</span></span><br><span class="line"><span class="class">        &quot;<span class="title">lifetime</span>&quot; =&gt; 86400,</span></span><br><span class="line"><span class="class">        &quot;<span class="title">prefix</span>&quot; =&gt; &#x27;<span class="title">sess</span>-<span class="title">ph</span>-&#x27;,</span></span><br><span class="line"><span class="class">    ], $<span class="title">this</span>-&gt;<span class="title">getConfig</span>()-&gt;<span class="title">redis</span>-&gt;<span class="title">toArray</span>()[0])) <span class="keyword">extends</span> <span class="title">SessionRedis</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">private</span> <span class="variable">$userSid</span> = <span class="string">&quot;&quot;</span>;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@return</span> string</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getUserSid</span>(<span class="params"></span>): <span class="title">string</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;userSid;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@param</span> string $userSid</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">setUserSid</span>(<span class="params"><span class="keyword">string</span> <span class="variable">$userSid</span></span>)</span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="keyword">$this</span>-&gt;userSid = <span class="variable">$userSid</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 这个函数有用，不要删除</span></span><br><span class="line"><span class="comment">         * phalcon在session start时调用session_set_save_handler函数设置当前类作为session</span></span><br><span class="line"><span class="comment">         * 适配器，create_sid对SessionHandler::create_sid方法进行重写，在调用本类regenerateId时会调用php的session_regenerate_id函数。</span></span><br><span class="line"><span class="comment">         * session_regenerate_id函数内部调用适配器的create_sid方法生成sid，也就是这个方法，当前匿名类对外暴露sid的getter和setter方法实现</span></span><br><span class="line"><span class="comment">         * 自定义sid，方便控制sid生成和获取任意用户的session信息</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@return</span> string</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">create_sid</span>(<span class="params"></span>) :<span class="title">string</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">    </span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">empty</span>(<span class="keyword">$this</span>-&gt;getUserSid()))&#123;</span><br><span class="line">                <span class="comment">// 固定给一个无效的sessid, 这个无法解密，也就是说解密失败的sessid，可以认为就是游客</span></span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;guest_&quot;</span> . md5(<span class="string">&quot;pref_&quot;</span> . di()-&gt;get(<span class="string">&quot;request&quot;</span>)-&gt;getClientAddress(<span class="literal">true</span>));</span><br><span class="line">            &#125;</span><br><span class="line">    </span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;getUserSid();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="variable">$session</span>-&gt;setAdapter(<span class="variable">$redis</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="variable">$session</span>-&gt;start();</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="variable">$session</span>;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>redis存储session，提高效率，session服务对外开放setUserSid方法，用户登陆时重新生成session_id即可。可以在生成用户sid过程中对用户之前的sid进行清理，更新sid的同时，避免sid堆满内存。游客用户可以使用ip作为唯一sid，如果没有特殊需求，固定一个sid更好一点</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">$this</span>-&gt;session-&gt;getAdapter()-&gt;setUserSid(<span class="keyword">$this</span>-&gt;generateUserSessId(<span class="number">1</span>));</span><br><span class="line"><span class="keyword">$this</span>-&gt;session-&gt;regenerateId();</span><br><span class="line"><span class="keyword">$this</span>-&gt;session-&gt;set(<span class="string">&quot;user_info&quot;</span>, <span class="variable">$userInfo</span>);</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/15/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/15/">15</a><span class="page-number current">16</span><a class="page-number" href="/page/17/">17</a><span class="space">&hellip;</span><a class="page-number" href="/page/22/">22</a><a class="extend next" rel="next" href="/page/17/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
  </nav>

</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2021 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">山丘之王</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
